<template>
  <div id="cont" v-loading="loading">
    <el-radio-group v-model="uType" size="small" @change="switchUType">
      <el-radio label="1">管理员</el-radio>
      <el-radio label="2">会员</el-radio>
      <el-button icon="el-icon-refresh" size="small" @click="refresh"></el-button>
    </el-radio-group>
    <el-form ref="form" :model="queryParams" :inline="true" class="table-query-form">
      <el-form-item>
        <el-input v-model="queryParams.username" :clearable="true" size="small" placeholder="用户名或邮箱"></el-input>
      </el-form-item>
      <el-form-item v-if="uType == 2">
        <el-select v-model="queryParams.grade" size="small" placeholder="等级">
          <el-option
            v-for="it in grades"
            :key="it.id"
            :label="it.name"
            :value="it.value"
            align="left">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="queryParams.date"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button type="default" size="mini" icon="el-icon-refresh" @click="reset">重置</el-button>
      </el-form-item>
      <el-form-item class="table-tools">
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="addUser" v-if="uType == 1">添加管理员</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="list">
      <el-table-column type="selection" align="center" width="45"></el-table-column>
      <el-table-column prop="sort" label="序号" align="center" width="50"></el-table-column>
      <el-table-column prop="username" label="用户名" align="center" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="realname" label="真实姓名" align="center" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="mobile" label="手机号" align="center" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="email" label="邮箱" align="center" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="roles" label="角色" align="center" v-if="uType == 1">
        <template #default="scope">
          <template v-if="scope.row.roles">{{ scope.row.roles.name }}</template>
        </template>
      </el-table-column>
      <el-table-column label="会员等级" align="center" v-if="uType == 2">
        <template #default="scope">
          <span v-for="(it, i) in grades" :key="i">
            <template v-if="it.id == scope.row.grade">{{ it.label }}</template>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ dateTr(scope.row.date) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <span v-if="scope.row.status == 0" class="f-danger">冻结</span>
          <span v-else-if="scope.row.status == 1" class="f-success">正常</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button type="text" size="mini" icon="el-icon-edit" @click="update(scope.row)">编辑</el-button>
          <el-button type="text" size="mini" icon="el-icon-delete" @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 用户编辑模板 -->
    <el-dialog :title="title" v-model="isEdit" width="60%" :append-to-body="false">
      <el-form ref="form" :data="form" :inline="true" label-width="80px">
        <el-form-item label="用户名:">
          <el-input v-model="form.username" size="small"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名:">
          <el-input v-model="form.realname" size="small"></el-input>
        </el-form-item>
        <el-form-item label="手机号:">
          <el-input v-model="form.mobile" size="small"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:">
          <el-input v-model="form.email" size="small"></el-input>
        </el-form-item>
        <el-form-item label="用户角色:" v-if="uType == 1">
          <el-select v-model="form.roles" size="small" aria-placeholder="请选择">
            <el-option v-for="(it, k) in roles" :key="k" :label="it.name" :value="it._id" align="left"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态:">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">冻结</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="会员等级:" v-if="uType == 2">
          <el-radio-group v-model="form.grade">
            <el-radio v-for="(it, i) in grades" :key="i" :label="it.id">{{ it.label }}</el-radio>?
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码重置:" v-if="!isNew">
          <el-radio-group v-model="form.repass">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注:" >
          <el-input type="textarea" v-model="form.remark" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" size="mini" @click="ensure">确 定</el-button>
          <el-button size="mini" @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import app from '@/utils/index'
import { userAdd, userList, memList, userDel, userUpdate } from '@/api/user_api';
import { roleList } from '@/api/role_api';
import { gradeList } from '@/api/grade_api';
import { mapGetters } from 'vuex'

export default {
  name: 'list',
  data() {
    return {
      loading: false,
      list: [],  // 用户列表
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // username: '',
        // grade: null,
        // date: ''
      },
      uType: 1,
      roles: [],  // 角色列表
      grades: [],  // 用户等级
      isEdit: false,  // 控制弹窗
      isNew: false,  // 是否新增
      title: '',  // 弹窗标题
      form: {
        username: '',
        roles: '',
        grade: 0,
        status: 1,
        repass: 0,
        remark: ''
      },  // 表单内容
      menus: [],  // 菜单选项集合
      checkedMenu: []  // 默认选中菜单
    }
  },
  computed: {
    ...mapGetters({
      state_menus: 'menus',
      state_grades: 'grades'
    }),
    // getRoleName(val) {
    //   this.roles.map(item => {
    //     if(val === item.value) {
    //       return item.name;
    //     }
    //   })
    // }
  },
  filters: {
    getRoleName(val) {
      console.log(183, val)
    }
  },
  created() {
    const grades = this.state_grades;
    if(grades && grades.length > 0) {
      this.grades = grades;
    }else {
      this.getGrade();
    }
    console.log('177...', this.state_grades);
    const ns = this.state_menus;
    this.polyMenus(ns, this.menus);
    this.getRole();
    this.getAdminList();

    this.checkedMenu = ns;
  },
  mounted() {},
  methods: {
    dateTr(tm) {
      return app.dateTime(tm, {format: 'YY-MM-DD'});
    },
    getName(data) {
      console.log(202, data)
      return data.roles.name;
    },
    // reset
    reset() {
      this.isEdit = false;
      for(const k in this.form) {
        this.form[k] = '';
      }
    },
    // search
    search() {
      this.getAdminList();
    },
    addUser() {
      this.isEdit = true;
      this.isNew = true;
    },
    // 管理员/会员
    switchUType(evt) {
      this.uType = evt;
      console.log('219...', evt);
      if(evt === 1) {
        this.getAdminList();
      }else {
        this.getMemberList();
      }
    },
    // 等级列表
    getGrade() {
      gradeList().then(response => {
        const res = response.data;
        if(res.s) {
          res.d.forEach((it, i) => {
            it.sort = i+1;
          })
          this.grades = res.d;
        }
      })
    },
    // 管理员列表
    getAdminList() {
      userList(this.queryParams).then(response => {
        const res = response.data;
        if(res.s) {
          res.d.forEach((it, i) => {
            it.sort = i+1;
          })
          this.list = res.d;
        }
      })
    },
    // 会员列表
    getMemberList() {
      memList(this.queryParams).then(response => {
        const res = response.data;
        if(res.s) {
          res.d.forEach((it, i) => {
            it.sort = i+1;
          })
          this.list = res.d;
        }
      })
    },
    // 整合菜单选择列表
    polyMenus(data, me) {

      data.map((it, i) => {
        const tmp = { id: it.meta.id, label: it.meta.title };
        me.push(tmp);
        if(it.children) {
          tmp.children = [];
          this.polyMenus(it.children, tmp.children);
        }
      })
    },
    // 菜单选择
    checked(data) {
      const menu = this.$refs['tree'].getCheckedKeys();
      this.form.menus = menu;
    },
    // 获取角色列表
    getRole() {
      roleList().then(response => {
        const res = response.data;
        if(res.s) {
          console.log('223...', res.d);
          
          this.roles = res.d.filter(item => { return item.value != 0; });
        }
      })
    },
    // 编辑用户
    update(data) {
      this.isEdit = true;
      this.isNew = false;
      this.title = '编辑';
      this.form = {
        id: data.id,
        username: data.username,
        realname: data.realname,
        mobile: data.mobile,
        email: data.email,
        roles: data.roles,
        grade: data.grade,
        status: data.status,
        repass: 0,
        remark: data.remark
      };
    },
    // 弹窗操作
    ensure() {
      if(this.isNew) {
        userAdd(this.form).then(response => {
          const res = response.data;
          if(res.s) {
            this.$message.success('添加成功！');
            this.getAdminList();
            this.reset();
          }else {
            this.$message.error('添加失败！')
          }
        })
      }else {
        userUpdate(this.form).then(response => {
          const res = response.data;
          if(res.s) {
            this.$message.success('修改成功！');
            this.getAdminList();
            this.reset();
          }else {
            this.$message.error('修改失败！')
          }
        })
      }
    },
    // delete user
    del(data) {
      this.$confirm('是否确定要删除用户？', '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '再想想',
        type: 'warning'
      }).then(() => {
        userDel({id: data.id}).then(response => {
          const res = response.data;
          if(res.s == 1) {
            this.$message.success('删除成功！');
            this.getAdminList();
          }else {
            this.$message.warning('删除失败！');
          }
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消删除！'
        })
      })
    },
    refresh() {
      this.getAdminList();
    },
    // 关闭弹窗
    cancel() {
      this.reset();
    }
  }
}
</script>

<style lang="less">
  .table-query-form {
    .el-input {
      width: 160px;
    }
    .el-date-editor {
      width: 240px;
    }
  }
  .table-tools {
    float: right;
    margin-right: 0 !important;
  }
  .el-radio__label {
    font-size: 13px;
  }
  .el-dialog {
    .el-input {
      width: 240px;
    }
  }
</style>